package com.example.zhu.Filter;

import com.alibaba.fastjson.JSON;
import com.example.zhu.Utils.JwtUtils;
import com.example.zhu.Utils.UserHolder;
import com.example.zhu.dto.Reply;
import com.example.zhu.dto.ResultCode;
import com.example.zhu.dto.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//坑点，路径是"/*"，别忘了*
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符，别忘了
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, ServletException, IOException {
        //0.要先把请求响应ServletXxx转成它的子接口HttpServletXxx，从而多了一些针对于Http协议的方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
 
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            filterChain.doFilter(request,response);
            return;
        }
        log.info("拦截到请求：{}",requestURI);
 
        //定义不需要处理的请求路径，前端页面可以放行，只是除登录登出的后端拦截就行。
        String[] urls = new String[]{
                "/auth/login",
        };
 
 
        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
 
        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //1、获取请求头
        String token = request.getHeader("Authorization");
        if(token.equals("")){
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control","no-cache");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(new ObjectMapper().writeValueAsString(Reply.failed(ResultCode.NO_LOGIN.getCode(), null)));
            response.getWriter().flush();
            return;
        }
        //2、使用工具类，判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        //3、如果token失效，返回状态码401，拦截
        if(!verifyToken) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Reply.failed(ResultCode.TOKEN_EXPIRED.getCode(), "登录状态失效", null)));
            response.setHeader("Cache-Control","no-cache");
            response.getWriter().flush();
            return;
        }else {
            //4、如果token正常可用，放行
            //解析token，获取id和手机号码，构造User对象，存入Threadlocal
            Claims claims = JwtUtils.getClaims(token);
            String username = (String) claims.get("username");
            User user = new User();
            user.setUsername(username);
            UserHolder.set(user);
            filterChain.doFilter(request,response);
            return;
        }
    }
 
    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            //这里是坑点，不能用equals
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}